package com.sunyy.codegenerator.controller;

import com.mybatisflex.core.query.QueryWrapper;
import com.sunyy.codegenerator.common.Message;
import com.sunyy.codegenerator.common.MyException;
import com.sunyy.codegenerator.dto.groupVariable.ListGroupVariableDto;
import com.sunyy.codegenerator.dto.groupVariable.SaveGroupVariableDto;
import com.sunyy.codegenerator.entity.GroupVariable;
import com.sunyy.codegenerator.service.GroupVariableService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 模板变量声明控制层
 *
 * @author sunyy
 * @since 2025/7/19
 */
@Slf4j
@RestController
@RequestMapping("/groupVariable")
public class GroupVariableController {

    @Resource
    private GroupVariableService groupVariableService;

    /**
     * 新增分组内的变量
     */
    @PostMapping("/saveGroupVariable")
    public Message<?> add(@RequestBody SaveGroupVariableDto dto) {
        groupVariableService.saveGroupVariable(dto);
        return Message.okWithNothing();
    }

    /**
     * 删除变量
     */
    @PostMapping("/deleteGroupVariable")
    public Message<?> add(Long id) {
        if (id == null || id < 0) {
            throw new MyException("入参【id】非法!!");
        }
        groupVariableService.removeById(id);
        return Message.okWithNothing();
    }

    /**
     * 查询变量
     *
     * @param dto
     * @return
     */
    @PostMapping("/listGroupVariable")
    public List<GroupVariable> pageListGroupVariable(@RequestBody ListGroupVariableDto dto) {
        if (dto == null) {
            throw new MyException("入参不能为空!!");
        }
        if (dto.getGroupId() == null || dto.getGroupId() < 0) {
            throw new MyException("入参【groupId】非法!!");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("group_id", dto.getGroupId());
        if (dto.getPkid() != null) {
            wrapper.eq("pkid", dto.getPkid());
        }
        if (dto.getVariableName() != null) {
            wrapper.like("variable_name", dto.getVariableName());
        }
        if (dto.getVariableType() != null) {
            wrapper.like("variable_type", dto.getVariableType());
        }
        return groupVariableService.list(wrapper);
    }

}
